package is.ru.honn.rupin.data;

import is.ru.honn.rupin.domain.Board;
import is.ru.honn.rupin.domain.Pin;
import is.ru.honn.rupin.domain.User;
import is.ru.honn.rupin.service.PinService;
import is.ru.honn.rupin.service.PinServiceData;
import is.ruframework.data.RuData;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * User: gmatt
 * Date: 20.10.2012
 * Time: 02:38
 *
 * An SQL implementation of the BoardDataGateway interface
 */
public class BoardData extends RuData implements BoardDataGateway {
    /**
     * Adds a board to the database
     * @param board Passes the board to be added to the database to the function
     */
    public void add(Board board) {
        SimpleJdbcInsert insertBoard =
                new SimpleJdbcInsert(getDataSource())
                        .withTableName("ru_boards")
                        .usingGeneratedKeyColumns("id");
        Map<String, Object> parameters = new HashMap<String, Object>(4);
        JdbcTemplate queryResult = new JdbcTemplate(getDataSource());
        parameters.put("boardname", board.getName());
        parameters.put("category", board.getCategory());
        parameters.put("username", board.getCreator().getUsername());
        parameters.put("created", board.getCreated());
        try{
            insertBoard.execute(parameters);
        }catch(DuplicateKeyException e){
            log.info("Duplicate key in table");
        }
    }

    /**
     * Gets all boards created by the specified user
     * @param username username of the user
     * @return all boards by the user as a List
     */
    @Override
    public List<Board> getBoardsByUsername(String username) {
        JdbcTemplate queryContent = new JdbcTemplate(getDataSource());
        return (List<Board>)queryContent.query("SELECT * FROM ru_boards WHERE creator=?",
                new BoardRowMapper(), username);
    }

    /**
     * gets all boards with the specified name
     * @param boardname passes the boardname to the function
     * @return The first board on the list
     */
    @Override
    public Board getBoard(String boardname, String username) {
        JdbcTemplate queryContent = new JdbcTemplate(getDataSource());
        List<Board> b = queryContent.query("SELECT * FROM ru_boards WHERE boardname=? AND username=?",
                new BoardRowMapper(), new Object[]{boardname, username});
        if(b.size() > 0)
            return b.get(0);
        else return null;
    }

}